﻿using XcoAppSpaces.Contracts.Service;
using XcoAppSpaces.Contracts.Transport;
using XcoAppSpaces.Contracts.Logging;
using System;
using System.Collections.Generic;
using XcoAppSpaces.Contracts.Serialization;
namespace test.XcoAppSpaces.Core.Communication
{
    public class XcoCommunicationServiceMock : IXcoTransportService
    {
		public event MessageReceivedDelegate OnMessageReceived;

        List<XcoCommunicationServiceMock> serviceList;
        public void DirectConnect(XcoCommunicationServiceMock service)
        {
            serviceList.Add(service);
        }
        public void DirectReceive(XcoMessage msg, string remoteAddress)
        {
			//if (messageReceiverService != null)
			//{
			//    messageReceiverService.MessageReceived(msg, remoteAddress, this);
			//}
			if (OnMessageReceived != null)
				OnMessageReceived(msg, remoteAddress, this);
        }
        public XcoCommunicationServiceMock(int port)
        {
            addr = Environment.MachineName.ToLower() + ":" + port;
            serviceList = new List<XcoCommunicationServiceMock>();
        }

        //IXcoMessageReceiverService messageReceiverService  ;
        bool running = false;
        string addr = null;

        #region IXcoTransportService Members

   
        public bool Running
        {
            get { return running; }
        }

        public void Send(XcoMessage msg, string remoteAddress)
        {
            foreach (var item in serviceList)
            {
				if (item.LocalAddress == remoteAddress)
                {
                    item.DirectReceive(msg, addr); //set address from sender
                    break;
                }
                
            }
        }

        public string LocalAddress
        {
            get { return addr; }
        }

        public void Start()
        {  
			 running = true;
        }

        public void Stop()
        {
            running = false;
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            
        }

        #endregion

    	public void Initialize(IXcoServiceRegistry serviceRegistry)
    	{
    	}

		#region IXcoStatefulService Members


		public int StartPriority
		{
			get { return 0; }
		}

		#endregion
	}
}